package com.booktrade.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.booktrade.dto.BookSearchDTO;
import com.booktrade.entity.Books;
import com.booktrade.entity.BooksTags;
import com.booktrade.entity.Tags;
import com.booktrade.entity.Users;
import com.booktrade.mapper.BooksMapper;
import com.booktrade.mapper.UsersMapper;
import com.booktrade.service.IBooksService;
import com.booktrade.service.IBooksTagsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 书籍表，存储所有二手书籍的详细信息 服务实现类
 */
@Service
@RequiredArgsConstructor
public class BooksServiceImpl extends ServiceImpl<BooksMapper, Books> implements IBooksService {

    private final BooksMapper booksMapper;
    private final UsersMapper userMapper;
    private final IBooksTagsService booksTagsService;

    @Transactional
    @Override
    public void publish(Books books, Integer userId) {
        Users users = userMapper.selectById(userId);

//        if (users.getUserRole() != 2) {
//            throw new RuntimeException("只有卖家才能发布书籍");
//        }
        books.setSellerId(userId);
        this.save(books);
        List<Tags> tagsList = books.getTagsList();
        saveBookTags(tagsList, books.getId());
    }

    @Transactional
    @Override
    public void updateBook(Books books, Integer userId) {
        this.updateById(books);
        List<Tags> tagsList = books.getTagsList();
        booksTagsService.remove(new LambdaQueryWrapper<BooksTags>().eq(BooksTags::getBookId, books.getId()));
        saveBookTags(tagsList, books.getId());

    }

    @Override
    public Page<Books> listBooksPage(BookSearchDTO bookSearchDTO) {
        Page<Books> page = this.page(new Page<>(bookSearchDTO.getCurrent(), bookSearchDTO.getPageSize()),
                new LambdaQueryWrapper<Books>()
                        .eq(bookSearchDTO.getCategory() != null && !bookSearchDTO.getCategory().equals(""),
                                Books::getCategory, bookSearchDTO.getCategory())
                        .like(bookSearchDTO.getSearchValue() != null && !bookSearchDTO.getSearchValue().equals(""),
                                Books::getTitle, bookSearchDTO.getSearchValue()).or()
                        .like(bookSearchDTO.getSearchValue() != null && !bookSearchDTO.getSearchValue().equals(""),
                                Books::getAuthor, bookSearchDTO.getSearchValue())
                        .lt(bookSearchDTO.getPrice() != null && bookSearchDTO.getPrice().compareTo(BigDecimal.ZERO) != 0,
                                Books::getPrice, bookSearchDTO.getPrice())
                        .orderByAsc(bookSearchDTO.getPrice() != null, Books::getPrice)
        );
        return page;
    }

    private void saveBookTags(List<Tags> tagsList, Integer bookId) {
        if (CollectionUtil.isNotEmpty(tagsList)) {
            List<BooksTags> booksTagsList = tagsList.stream().map(t -> {
                BooksTags booksTags = new BooksTags();
                booksTags.setBookId(bookId);
                booksTags.setTagId(t.getId());
                return booksTags;
            }).collect(Collectors.toList());
            booksTagsService.saveBatch(booksTagsList);
        }
    }
}
